//
//  UIView+YGGestureBlock.m
//  UIKit分类整合
//
//  Created by Mr.xu on 2017/1/8.
//  Copyright © 2017年 xuyaguang. All rights reserved.
//

#import "UIView+YGGestureBlock.h"
#import <objc/runtime.h>

static char ygActionHandlerTapBlockKey;
static char ygActionHandlerTapGestureKey;
static char ygActionHandlerLongPressBlockKey;
static char ygActionHandlerLongPressGestureKey;


@implementation UIView (YGGestureBlock)


- (void)yg_addTapActionWithBlock:(TapActionBlock)block
{
    UITapGestureRecognizer *gesture = objc_getAssociatedObject(self, &ygActionHandlerTapGestureKey);
    if (!gesture)
    {
        gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(yg_handleActionForTapGesture:)];
        [self addGestureRecognizer:gesture];
        objc_setAssociatedObject(self, &ygActionHandlerTapGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
    }
    objc_setAssociatedObject(self, &ygActionHandlerTapBlockKey, block, OBJC_ASSOCIATION_COPY);
}

- (void)yg_handleActionForTapGesture:(UITapGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateRecognized)
    {
        TapActionBlock block = objc_getAssociatedObject(self, &ygActionHandlerTapBlockKey);
        if (block)
        {
            block(gesture);
        }
    }
}

- (void)yg_addLongPressActionWithBlock:(LongPressActionBlock)block
{
    UILongPressGestureRecognizer *gesture = objc_getAssociatedObject(self, &ygActionHandlerLongPressGestureKey);
    if (!gesture)
    {
        gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(yg_handleActionForLongPressGesture:)];
        [self addGestureRecognizer:gesture];
        objc_setAssociatedObject(self, &ygActionHandlerLongPressGestureKey, gesture, OBJC_ASSOCIATION_RETAIN);
    }
    objc_setAssociatedObject(self, &ygActionHandlerLongPressBlockKey, block, OBJC_ASSOCIATION_COPY);
}

- (void)yg_handleActionForLongPressGesture:(UILongPressGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateRecognized)
    {
        LongPressActionBlock block = objc_getAssociatedObject(self, &ygActionHandlerLongPressBlockKey);
        if (block)
        {
            block(gesture);
        }
    }
}

@end
